#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<stdlib.h>

//初始化条件变量
pthread_cond_t   cond = PTHREAD_COND_INITIALIZER;
//初始化互斥量
pthread_mutex_t  lock = PTHREAD_MUTEX_INITIALIZER;


//同步资源
char Cur_Thread = 'A';

void * printThreadId(void * arg){
	char tmpThread = *(char *)arg;
	int count = 10;
	pthread_detach(pthread_self());

	while(count--){
		pthread_mutex_lock(&lock);

		while(Cur_Thread != tmpThread){
			pthread_cond_wait(&cond, &lock);
		}

		printf("%c", tmpThread);
		fflush(stdout);

		if(tmpThread == 'A'){
			Cur_Thread = 'B';
		}else if(tmpThread == 'B'){
			Cur_Thread = 'C';
		}else{
			//tmpThread == 'C'
			Cur_Thread = 'A';
		}
		
		pthread_cond_broadcast(&cond);

		pthread_mutex_unlock(&lock);

		usleep(100000);
	}
	return NULL;
}


int main(){
	pthread_t  tida, tidb, tidc;
	char tid_a = 'A';
	char tid_b = 'B';
	char tid_c = 'C';
	
	pthread_create(&tida, NULL, printThreadId, (void *)&tid_a);
	pthread_create(&tidb, NULL, printThreadId, (void *)&tid_b);
	pthread_create(&tidc, NULL, printThreadId, (void *)&tid_c);

	// 等待三个线程结束
    pthread_join(tida, NULL);
    pthread_join(tidb, NULL);
    pthread_join(tidc, NULL);

    // 销毁互斥锁和条件变量
    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&cond);

    printf("\n");
    return 0;

}
